<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="UTF-8">
        <title>更新页面</title>
        <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
        <link rel="stylesheet" href="/app/admin/component/jsoneditor/css/jsoneditor.css" />
        <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
        
    </head>
    <body>

        <form class="layui-form">

            <div class="mainBox">
                <div class="main-container mr-5">
                    <div class="layui-form-item">
                        <label class="layui-form-label required">章节名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" placeholder="" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label required">章节序号</label>
                        <div class="layui-input-block">
                            <input type="number" name="number" placeholder="" class="layui-input">
                        </div>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 50%">
                            <label class="layui-form-label required">原文内容</label>
                            <div class="layui-input-block">
                                <tip style="color: red"> 当前字数：<span class="original_char_nums">0</span></tip>
                                <textarea name="original_content" class="layui-textarea" rows="15" cols="27" onblur="comput_original_nums()"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item"  style="width: 50%;display: flex;flex-direction: row;">
                            <div style="display: flex;flex-direction: column;">
                                <label class="layui-form-label">原文分析AI指令：</label>
                                <button type="button" class="layui-btn layui-btn-radius edit_original_content_ai_command" style="margin-left: 9px">
                                    更新指令
                                </button>
                            </div>
                            <div class="layui-input-block" style="margin-left: 10px;">
                                <tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>
                                <textarea name="original_content_ai_command" class="layui-textarea" rows="15" cols="100"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md original_content_analyze">
                            原文分析
                        </button>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 50%">
                            <label class="layui-form-label required">分析内容</label>
                            <div class="layui-input-block">
                                <tip style="color: red"> 当前字数：<span class="analyze_char_nums">0</span></tip>
                                <textarea name="analyze_content" class="layui-textarea" rows="15" cols="27" onblur="comput_analyze_nums()"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item"  style="width: 50%;display: flex;flex-direction: row;">
                            <div style="display: flex;flex-direction: column;">
                                <label class="layui-form-label">内容换行AI指令：</label>
                                <button type="button" class="layui-btn layui-btn-radius edit_content_parts_ai_command" style="margin-left: 9px">
                                    更新指令
                                </button>
                            </div>
                            <div class="layui-input-block"  style="margin-left: 10px;">
                                <tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>
                                <textarea name="content_parts_ai_command" class="layui-textarea" rows="15" cols="100"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md analyze_content_parts">
                            内容分段
                        </button>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 50%;">
                            <label class="layui-form-label required">分段内容</label>
                            <div class="layui-input-block">
                                <tip style="color: red">换行作为分段的隔离符   当前段落数：<span class="part_nums">0</span></tip>
                                <textarea name="content" class="layui-textarea" rows="15" cols="27" onblur="comput_part_nums()"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item"  style="width: 50%;display: flex;flex-direction: row;">
                            <div style="display: flex;flex-direction: column;">
                                <label class="layui-form-label">生成描述词AI指令：</label>
                                <button type="button" class="layui-btn layui-btn-radius edit_batch_prompt_ai_command" style="margin-left: 9px">
                                    更新指令
                                </button>
                            </div>
                            <div class="layui-input-block" style="margin-left: 10px;">
                                <tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>
                                <textarea name="batch_prompt_ai_command" class="layui-textarea" rows="15"  cols="100"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" style="display: none;">
                        <label class="layui-form-label required">GPT版本</label>
                        <div class="layui-input-block gptversion">
                            <input type="radio" name="name" value="gpt-4" title="gpt-4" checked>
                            <input type="radio" name="name" value="gpt-3" title="gpt-3">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md batch_regenerate_prompt">
                            批量生成英文描述词
                        </button>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">英文描述词</label>
                        <div class="layui-input-block">
                            <tip style="color: red">当前段落数：<span class="analyze_part_nums">0</span></tip>
                            <textarea name="prompt_content" class="layui-textarea" rows="15" cols="80" onblur="comput_analyze_part_nums()"></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bottom">
                <div class="button-container">
                    <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit="" lay-filter="save">
                        提交
                    </button>
                    <!--<button type="reset" class="pear-btn pear-btn-md">-->
                        <!--重置-->
                    <!--</button>-->
                </div>
            </div>
            <div style="display: none;">
                <textarea name="original_content_ai_command_config" class="layui-textarea" rows="15"  cols="23"><?=htmlspecialchars($original_content_ai_command)?></textarea>
                <textarea name="content_parts_ai_command_config" class="layui-textarea" rows="15"  cols="23"><?=htmlspecialchars($content_parts_ai_command)?></textarea>
                <textarea name="batch_prompt_ai_command_config" class="layui-textarea" rows="15"  cols="23"><?=htmlspecialchars($batch_prompt_ai_command)?></textarea>
            </div>
        </form>

        <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
        <script src="/app/admin/component/pear/pear.js"></script>
        <script src="/app/admin/component/jsoneditor/jsoneditor.js"></script>
        <script src="/app/admin/admin/js/permission.js"></script>
        <script src="/app/admin/admin/js/functions.js"></script>
        <script src="/app/admin/admin/js/md5.js"></script>
        
        <script>
            // 相关接口
            const PRIMARY_KEY = "id";
            const PRIMARY_KEY_VALUE = layui.url().search[PRIMARY_KEY];
            const LANG_VALUE = layui.url().search['lang'];
            const SELECT_API = "/app/admin/novel/chapter/select" + location.search;
            const UPDATE_API = "/app/admin/novel/chapter/update";
            const AI_REGENERATE_API = "/app/admin/novel/chapter/airegenerate";
            const GPT_SELECT_API = "/app/admin/gptversion/index/select?limit=100";

            // 获取数据库记录
            layui.use(["form", "util", "popup"], function () {
                $ = layui.$;
                let loading = layer.load();
                $.ajax({
                    url: SELECT_API,
                    dataType: "json",
                    async:true,
                    headers: get_header({"id":PRIMARY_KEY_VALUE,"lang":LANG_VALUE}),
                    success: function (res) {
                        layer.close(loading);
                        // 给表单初始化数据
                        layui.each(res.data[0], function (key, value) {
                            let obj = $('*[name="'+key+'"]');
                            if (key === "password") {
                                obj.attr("placeholder", "不更新密码请留空");
                                return;
                            }
                            if (typeof obj[0] === "undefined" || !obj[0].nodeName) return;
                            if (obj[0].nodeName.toLowerCase() === "textarea") {
                                obj.val(value);
                            } else {
                                obj.attr("value", value);
                                obj[0].value = value;
                            }
                        });


                        let param = {"status":1};
                        layui.$.ajax({
                            url: GPT_SELECT_API,
                            type: "GET",
                            dateType: "json",
                            data: param,
                            async:true,
                            headers: get_header(param),
                            success: function (res2) {

                                if (res2.code) {
                                    return layui.popup.failure(res2.msg);
                                }
                                let html ='';
                                let checked ='';
                                layui.$.each(res2.data,function (i,v) {
                                    checked ='';
                                    if(res.data[0]['gptversion'] && res.data[0]['gptversion']==v['name']){
                                        checked ='checked';
                                    }else if(res.data[0]['gptversion']==false && v['name']=='gpt-4o'){
                                        checked ='checked';
                                    }
                                    html += '<input type="radio" name="gptversion" value="'+v['name']+'" title="'+v['name']+'" '+checked+'>';
                                })
                                $('.gptversion').html(html);

                                layui.form.render();
                            }
                        });

                        comput_original_nums()
                        comput_analyze_nums()
                        comput_part_nums()
                        comput_analyze_part_nums()

                        // ajax返回失败
                        if (res.code) {
                            layui.popup.failure(res.msg);
                        }
                        
                    }
                });
            });

            //提交事件
            layui.use(["form", "popup","loading"], function () {
                layui.form.on("submit(save)", function (data) {
                    let prompt_content = layui.$('textarea[name="prompt_content"]').val();
                    let prompt_contents = prompt_content.split("\n");
                    let content = layui.$('textarea[name="content"]').val();
                    let contents = content.split("\n");
                    if(prompt_contents.length!=contents.length){
                        layer.msg('创作章节段落和英文描述词段落不一致',{"icon":2,"time":2000});
                        return false;
                    }

                    data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
                    let loading = layer.load();
                    layui.$.ajax({
                        url: UPDATE_API,
                        type: "POST",
                        dateType: "json",
                        data: data.field,
                        async:true,
                        headers: get_header(data.field),
                        success: function (res) {
                            layer.close(loading);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                parent.refreshTable();
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                            });
                        }
                    });
                    return false;
                });

                // layui.form.on("submit(regenerate_chapter)", function (data) {
                //     data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
                //     data.field['type'] = 'regenerate_chapter';
                //     let loadIndex = layui.loading.Load(1, "生成中...");
                //     layui.$.ajax({
                //         url: AI_REGENERATE_API,
                //         type: "POST",
                //         dateType: "json",
                //         data: data.field,
                //         async:true,
                //         headers: get_header(data.field),
                //         success: function (res) {
                //             layui.loading.loadRemove(1);
                //             if (res.code) {
                //                 return layui.popup.failure(res.msg);
                //             }
                //             return layui.popup.success("操作成功", function () {
                //                 layui.$('textarea[name="analyze_content"]').val(res.data.analyze_content);
                //                 layui.$('.analyze_part_nums').text(res.data.part_nums);
                //                 comput_analyze_part_nums()
                //             });
                //         },
                //         error:function (res) {
                //             layui.loading.loadRemove(1);
                //             return layui.popup.failure('请求失败');
                //         }
                //     });
                //     return false;
                // });
            });

            layui.use(["form", "popup","loading"], function () {
                layui.$('.original_content_analyze').click(function () {
                    let param = {};
                    param['original_content'] = layui.$('textarea[name="original_content"]').val();
                    param['original_content_ai_command'] = layui.$('textarea[name="original_content_ai_command"]').val();
                    param['type'] = 'original_content_analyze';

                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: param,
                        async:true,
                        headers: get_header(param),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="analyze_content"]').val(res.data.analyze_content);
                                layui.$('.analyze_char_nums').text(res.data.analyze_nums);
                                comput_analyze_nums()
                            });
                        },
                        error:function (res) {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                })

                layui.$('.analyze_content_parts').click(function () {
                    let param = {};
                    param['analyze_content'] = layui.$('textarea[name="analyze_content"]').val();
                    param['content_parts_ai_command'] = layui.$('textarea[name="content_parts_ai_command"]').val();
                    param['type'] = 'analyze_content_parts';

                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: param,
                        async:true,
                        headers: get_header(param),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="content"]').val(res.data.content);
                                layui.$('.part_nums').text(res.data.part_nums);
                                comput_part_nums()
                            });
                        },
                        error:function (res) {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                })

                layui.$('.batch_regenerate_prompt').click(function () {
                    let param = {};
                    param[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
                    param['content'] = layui.$('textarea[name="content"]').val();
                    param['gptversion'] = layui.$('input[name="gptversion"]:checked').val();
                    param['batch_prompt_ai_command'] = layui.$('textarea[name="batch_prompt_ai_command"]').val();
                    param['type'] = 'batch_regenerate_prompt';

                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: param,
                        async:true,
                        headers: get_header(param),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="prompt_content"]').val(res.data.prompt_content);
                                layui.$('.analyze_part_nums').text(res.data.part_nums);
                                comput_analyze_part_nums()
                            });
                        },
                        error:function (res) {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                })

                layui.$('.edit_original_content_ai_command').click(function () {
                    layui.$('textarea[name="original_content_ai_command"').val(layui.$('textarea[name="original_content_ai_command_config"').val());
                });
                layui.$('.edit_content_parts_ai_command').click(function () {
                    layui.$('textarea[name="content_parts_ai_command"').val(layui.$('textarea[name="content_parts_ai_command_config"').val());
                });
                layui.$('.edit_batch_prompt_ai_command').click(function () {
                    layui.$('textarea[name="batch_prompt_ai_command"').val(layui.$('textarea[name="batch_prompt_ai_command_config"').val());
                });
            });

            function comput_original_nums() {
                let content = layui.$('textarea[name="original_content"]').val();
                let contents = content.split("\n");
                let nums = 0;
                let contentVal = '';
                $.each(contents,function (i,v) {
                    let text = v.replace(/[·|`|~|!|@|#|\$|\^|\&|\*|(|)|=|\||{|}|'|\\|\[|\]|<|>|《|》|\/|￥|……|（|）|——|_|+|-|{|}|【|】|‘|”|“|’|「|」]+/g,'');
                    text = text.replace(/^\d+[\.]*/,'');
                    if(text){
                        nums++;
                        contentVal += text+"\n";
                    }
                })
                layui.$('textarea[name="original_content"]').val(contentVal);

                $('.original_char_nums').text(getChineseLength(contentVal));
            }

            function comput_analyze_nums() {
                let content = layui.$('textarea[name="analyze_content"]').val();
                let contents = content.split("\n");
                let nums = 0;
                let contentVal = '';
                $.each(contents,function (i,v) {
                    let text = v.replace(/[·|`|~|!|@|#|\$|\^|\&|\*|(|)|=|\||{|}|'|\\|\[|\]|<|>|《|》|\/|￥|……|（|）|——|_|+|-|{|}|【|】|‘|”|“|’|「|」]+/g,'');
                    text = text.replace(/^\d+[\.]*/,'');
                    if(text){
                        nums++;
                        contentVal += text+"\n\n";
                    }
                })
                layui.$('textarea[name="analyze_content"]').val(contentVal);
                $('.analyze_char_nums').text(getChineseLength(contentVal));
            }

            function comput_part_nums() {
               let content = layui.$('textarea[name="content"]').val();
               let contents = content.split("\n");
               let nums = 0;
               let contentVal = '';
               $.each(contents,function (i,v) {
                   let text = v.replace(/[·|`|~|!|@|#|\$|\^|\&|\*|(|)|=|\||{|}|'|\\|\[|\]|<|>|《|》|\/|￥|……|（|）|——|_|+|-|{|}|【|】|‘|”|“|’|「|」]+/g,'');
                   text = text.replace(/^\d+[\.]*/,'');
                   if(text.length>1){
                       nums++;
                       contentVal += (parseInt(nums))+'.'+ text+"\n";
                   }
               })
                layui.$('textarea[name="content"]').val(contentVal);
               $('.part_nums').text(nums);
            }

            function comput_analyze_part_nums() {
               let content = layui.$('textarea[name="prompt_content"]').val();
               let contents = content.split("\n");
               let nums = 0;
                let contentVal = '';
               $.each(contents,function (i,v) {
                   let text = v.replace(/^[ ]*/,'');
                   text = text.replace(/^\d+[\.]*/,'');
                   //console.log(text.length);
                   if(text.length>1){
                       //console.log(text.length);
                       nums++;
                       contentVal += (parseInt(nums))+'.'+ text+"\n";
                   }
               })
                layui.$('textarea[name="prompt_content"]').val(contentVal);
               $('.analyze_part_nums').text(nums);

                if(parseInt($('.part_nums').text())!=nums){
                    layer.msg('创作章节段落和英文描述词段落不一致',{"icon":2,"time":2000});
                }
            }
        </script>

    </body>

</html>
